# to include the current developing tkMD into tcl package search path. Wouldn't be needed for deploy.
set auto_path [concat [pwd]/../../pkg/tkMD $auto_path ]
##\verbatim
## start of the program
package require tkMD 1.1
namespace import Path::*
namespace import Data::*

if { [llength $argv] == 2 } {
  set collectpath [lindex $argv 0]
} else {
   puts "Usage example: collect.tcl collectpath"
  exit
}

## Important variables: 
set pattern $collectpath/@peptide/anfr_@anfr/r0_@r0/k0_@k0/run
set Collect_Criteria ENERGY
set savepath $collectpath/pdb
set collectfile eql_en_min.pdb
set savepath $collectpath/[string map {. _} $collectfile]

## Start Collecting PDB files with minimum energy.
# if you write energy information into the header in a format like "ENERGY=121"
# this energy will be collected
proc getener { pdbfile } {
   set line [exec grep "=" $pdbfile ]
   set dlist [regexp -inline -all -- {\S+} $line ]
   set idxs [lsearch -all $dlist = ]
   array set Var {}
   foreach idx $idxs {
   set name [lindex $dlist [expr $idx -1]]
   set value [lindex $dlist [expr $idx +1]]
   set Var($name) $value
   }
   set result [array get Var]
   lappend result path
   lappend result $pdbfile
   return $result
}

## Collect the pdb files for energy using the procedure getener 
set result [Data::collect $collectpath eql_en_min.pdb $pattern getener]

## find the file with lowest energy in each variable value comination.
foreach {key vargroups} $result {
    set minener 99999
    foreach vargroup $vargroups {
       set ener [dict get $vargroup $Collect_Criteria]
       if { $ener < $minener } {
            set minener $ener
            set minpath [dict get $vargroup path]
       }
    }
    dict set pathresult $key $minpath
}
## Finally, execuate the copying.
foreach {pair path } $pathresult {
    set newpath $savepath/
    foreach { var value} $pair {
       append newpath $var=${value}_
    }
    append newpath $collectfile
    Path::mk_path [file dirname $newpath]
    puts "Copying $path to $newpath..."
    if [ catch {exec cp $path $newpath } error ] { puts "Warning: copy $path failed!\n $error" }
}
##\endverbatim
exit

